/**
 * Created by baiguiren on 2/8/17.
 */

let helper      = require('../common/helper');
let md5         = require('md5');
let async       = require('async');
let knex        = require('../common/knex').knex;
let config      = require('../config');
let eventproxy  = require('eventproxy');
let smsService  = require('../services/SmsService');
let userService = require('../services/userService');
let _           = require('lodash');

const category = 'tb_category';
const view_goods = 'tb_view_goods';
const view_order_goods = 'tb_view_order_goods';

exports = module.exports = {
  //获取分类列表, 包含子分类
  category: function (req, res) {
    knex.where({
      is_deleted: 0,
      status: 1
    }).where('pid', -1)
      .orderBy('sort_index')
      .select('id', 'name', 'sort_index')
      .from(category)
      .then(function (categories) {
        async.each(categories, function (cate, callback) {
          knex.where({
            is_deleted: 0,
            status: 1
          }).where('pid', cate.id)
            .orderBy('sort_index')
            .select('id', 'pid', 'name', 'sort_index')
            .from(category)
            .then(function (sub_cate) {
              cate.sub_category = sub_cate;
              callback(null);
            });
        }, function (err) {
          return res.send(helper.apiSuccess(categories));
        });
      })
  },

  //获取商品列表
  goodsList: function (req, res) {
    let ep = new eventproxy();
    let category_id = req._params.category_id || -1;
    let server_time = req._params.server_time || helper.time();
    let builder = knex(view_goods).where({
      is_deleted: 0,
      status: 1
    }).orderBy('sort_index');
    knex(category)
      .where({is_deleted: 0, status: 1})
      .orderBy('sort_index')
      .where('id', category_id)
      .first()
      .then(function (target_category) {
        if (target_category && target_category.pid <= 0) {
          //顶级分类
          knex(category)
            .where({is_deleted: 0, status: 1})
            .orderBy('sort_index')
            .where('pid', target_category.id)
            .pluck('id')
            .then(function (ids) {
              builder = builder.whereIn('category_id', ids);
              ep.emit('db_builder')
            });
        } else if (category_id == -1) {
          //没有选择分类, 显示排序第一的顶级分类
         knex(category).where({is_deleted: 0, status: 1})
          .orderBy('sort_index').where('pid', -1).first().then(function (result) {
            if (result) {
              knex(category).where({is_deleted: 0, status: 1}).orderBy('sort_index').where('pid', result.id)
                .pluck('id').then(function (ids) {
                  builder = builder.whereIn('category_id', ids);
                  ep.emit('db_builder');
              });
            } else {
              //一个分类都没有
              builder = builder.where('category_pid', result.id);
              ep.emit('db_builder');
            }
          })
        } else {
          //二级分类
          builder = builder.where('category_id', category_id);
          ep.emit('db_builder');
        }
      });
    ep.all('db_builder', function () {
      builder.where('create_time', '<', server_time)
        .orderBy('create_time', 'desc')
        .paginate(config.api_page_size, req._params.page || 1,
          ['id', 'category_id', 'category_pid', 'name', 'unit_price', 'image',
          'desc', 'sales', 'extra_sales', 'intro', 'sort_index'])
        .then(function (result) {
          if (result) {
            //let sales_count;
            async.each(result.data, function (data, callback) {
              //统计月销量, 实际月销量+额外销量
              getSalesCount(data.id).then(function (sum) {
                data.sales = sum + data.extra_sales;
                delete data.extra_sales;
                //替换图片url, 使用请求api的url代替
                //todo 返回缩略图路径
                // $value['image'] = wrap_image_url($value['image'], ['width'=>160, 'height'=>160]);
                callback(null);
              });

              // data.sales = getSalesCount(data.id) + data.extras;
              // delete data.extra_sales;
              //
              // //替换图片url, 使用请求api的url代替
              // //todo 返回缩略图路径
              // // $value['image'] = wrap_image_url($value['image'], ['width'=>160, 'height'=>160]);
              // callback(null);
            }, function (err) {
              return res.send(helper.apiSuccess(result));
            });
          } else {
            return res.send(helper.apiSuccess())
          }
        }).catch(function (err) {
          //console.log(err);
          return res.send(helper.apiFail(err));
        })
    });
  },

  //获取商品详情
  //商品轮播图片列表
  goodsInfo: function (req, res) {
    let goods_id = req._params.goods_id;
    if (helper.has_empty(goods_id)) {
      return res.send(helper.apiMissRequiredParams());
    }
    let ep = new eventproxy();

    knex(view_goods).where({
      is_deleted: 0,
      status: 1
    }).orderBy('sort_index')
      .where('id', goods_id)
      .first()
      .then(function (goods) {
        if (!goods) {
          return res.send(helper.apiFail('商品不存在'));
        } else if (goods.status == 0 || goods.is_deleted == 1) {
          goods.is_exist = 0;
          return res.send(helper.apiSuccess('商品不存在', goods));
        } else {
          goods.is_exist = 1;
          //goods.sales_count = getSalesCount(goods.id);
          getSalesCount(goods.id).then(function (sales_count) {
            ep.emit('get_sales_count', sales_count);
          });

          //todo 替换图片url, 使用请求api的url代替
          //$goods['image'] = wrap_image_url($goods['image'], ['width'=>160, 'height'=>160]);

          knex('tb_all_images').where({
            target_table_name: 'goods',
            target_id: goods.id
          }).pluck('path').then(function (paths) {
            //todo 替换图片url
            // foreach ($images as &$image) {
            //   $image = wrap_image_url($image, ['width'=>750, 'height'=>500]);
            // }
            //paths = paths.slice(0, 4);
            //goods.images = paths.join(',');
            //goods.sales = getSalesCount(goods.id) + goods.extra_sales;
            //delete goods.extra_sales;

            ep.emit('get_images', paths);
            //return res.send(helper.apiSuccess(goods));
          });
          
          ep.all('get_sales_count', 'get_images', function (sales_count, paths) {
            goods.sales_count = sales_count;
            goods.sales = sales_count + goods.extra_sales;
            delete goods.extra_sales;
            goods.images = paths.slice(0, 4).join(',');
            return res.send(helper.apiSuccess(goods));
          });
        }
      })
  },

  //商品详情(H5页面)
  goodsDetail: function (req, res) {
    let token = req._params.token;
    let goods_id = req._params.goods_id;

    if (helper.strcmp(md5('goods_' + goods_id), token) !== 0) {
      return res.send(helper.apiFail('token错误'));
    }
    knex('tb_goods').where({
      is_deleted: 0,
      status: 1,
      id: goods_id
    }).first().then(function (goods) {
      if (!goods) {
        return res.send(helper.apiFail('商品不存在'));
      } else {
        return res.render('test', {detail: goods.detail});
      }
    })
  }
};

//统计过去一个月的销量
let getSalesCount = function (goods_id, interval = '') {
  return new Promise(function (resolve, reject) {
    let between_time = get_month_interval();
    let builder = knex(view_order_goods).where({
      pay_status: 1,
      goods_id: goods_id
    });
    if (interval != -1) {
      builder = builder.whereBetween('create_time', between_time);
    }

    builder.groupBy('goods_id').sum('amount as sum').first().then(function (result) {
      if (result) {
        resolve(result.sum);
      } else {
        resolve(0);
      }
    });
  })
};

//获取上一个月月份时间戳数组, [开始时间戳, 结束时间戳]
let get_month_interval = function () {
  let now = new Date();
  let year = now.getFullYear();
  let month = now.getMonth();
  let begin, end;

  if (month == 0) {
    //一月份
    begin = (new Date(year - 1, 11).getTime()).toString().substr(0, 10);
    end = (new Date(year, month + 1).getTime()).toString().substr(0, 10);
  } else if (month == 11){
    begin = (new Date(year, month - 1).getTime()).toString().substr(0, 10);
    end = (new Date(year + 1, month).getTime()).toString().substr(0, 10);
  } else {
    begin = (new Date(year, month - 1).getTime()).toString().substr(0, 10);
    end = (new Date(year, month + 1).getTime()).toString().substr(0, 10);
  }
  return [parseInt(begin), parseInt(end)];
};

let wrap_image_url = function($url, $size) {
  //return get_thumb_url($url, $size['width'], $size['height']);
};

/**
 * 根据原图路径和宽高获取缩略图路径, 如果缩略图存在返回缩略图路径
 * 不存在则制作缩略图并保存(前提是原图存在)
  path 原图路径
  width 缩略图宽度
  height 缩略图高度
 */
// let get_thumb_url = function(path, width, height) {
//   if (path == '') {
//     return '';
//   }
//   $img_file_name = basename($path);
//   $dir_name = dirname($path);
//   $img_file_name_without_extension = explode('.', $img_file_name)[0];
//   $extension = explode('.', $img_file_name)[1];
//
//   $thumb_name = $img_file_name_without_extension . "_w$width". "_h$height". ".$extension";
//   if (file_exists(public_path($dir_name . "/" . $thumb_name))) {
//     return $dir_name . "/" . $thumb_name;
//   } else {
//     return img_url($path, $width, $height);
//   }
// }